<?php

namespace App\Http\Controllers\V1\Upload;

use App\Models\V1\Term;
use App\Models\V1\School;
use Illuminate\Http\Request;
use App\Http\Requests\V1\ImportDataRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Events\V1\ImportExportEvent;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Auth;
use Log;

class SchoolExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入学期数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '学校数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);

            $filePath = $request->input('successFile');
            $fileExtension = $request->input('extension');

            Excel::load($filePath, function($reader) use ($fileExtension) {
                $reader->limitColumns(6);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($fileExtension) {
                    $insert_data = [
                        'code' => $item[0],
                        'name' => $item[1],
                        'address' => $item[2],
                        'phone' => $item[3],
                        'province' => $item[4],
                        'city' => $item[5],
                    ];
                    if (!empty($item[0]) && !empty($item[1]) && !empty($item[2]) && !empty($item[3]) && !empty($item[4]) && !empty($item[5])) {
                        School::updateOrCreate(['code'=>$item[0]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出教学专业数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['学校代码', '学校名称','学校地址','联系方式','省份','城市'];
        $custodian = School::all(['code', 'name', 'address', 'phone','province','city']);
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->address,
                $item->phone,
                $item->province,
                $item->city,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create('学校', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('School', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[学校]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
